<?php
/**
 * Created by PhpStorm.
 * User: Lee
 * Date: 2019/12/18
 * Time: 15:25
 */
namespace App\Services\Backend\System;

use App\Common\Exception\ErrorException;
use App\Models\Backend\System\Group;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

/**
 * 系统管理-组 (服务)
 */
class GroupService
{
    /**
     * @var \App\Repositories\Backend\System\GroupRepository $groupRepository
     */
    private $groupRepository;

    public function __construct()
    {
        $this->groupRepository = app('groupRepository');;
    }

    //获取所有组别
    public function getAllGroup()
    {

        $menus = [];
        $school = Auth::user()->school();
        $menus[$school['id']] = [
            'name' => $school['group_name'],
            'value' => -1,
            'children' => [],
        ];
        $grades = DB::table('groups')->where('parent_id','=',$school['id'])->get();
        foreach ($grades as $grade){
            $gradeObject = [
                'value' => $grade->id,
                'name' => $grade->group_name,
                'children' =>[],
            ];
            $menus[$school['id']]['children'][$grade->id] = $gradeObject;
            $userRows = DB::table('users')->where('group_id','=',$grade->id)->where('active_flag','=',1)->limit(100)->get(['user_id','user_name']);
            if ($userRows->count() == 0){
                $menus[$school['id']]['children'][$grade->id]['disabled'] = true;
            }else{
                foreach ($userRows as $user){
                    $userObject = [
                        'value' => $user->user_id,
                        'name' => $user->user_name,
                    ];
                    $menus[$school['id']]['children'][$grade->id]['children'][$user->user_id] = $userObject;
                }
            }

        }



        $menus = array_values($menus);
        foreach($menus as $k => $v){
            $menus[$k]['children'] = array_values($menus[$k]['children']);

            foreach($menus[$k]['children'] as $k_g => $v_g){
                $menus[$k]['children'][$k_g]['children'] =  array_values( $menus[$k]['children'][$k_g]['children']);
            }
        }

        return $menus;
    }

    // 获取所有学校
    public function getAllSchool($columns = ['*']){

        $user = auth()->user();
        $cur_group_id = $user->group_id;
        $roles = $user->roles()->get();
        $isAdmin = $roles->whereIn('id', [MASTER_ROLEID,SYSTEMADMIN_ROLEID,DEPARTMENT_ROLEID]);
        if ($isAdmin->isEmpty()){
            //活动负责老师只能看自己
             $groupRow = $this->groupRepository->get($cur_group_id);
             if (!empty($groupRow)){
                 return [[
                     'id' => $groupRow->id,
                     'title'=>$groupRow->group_name
                 ]];
             }else{
                 return [];
             }
        }else{
            $filters = [];
            $filters[] = ['group_flag', '=', 1];
            $sort = ['id' => 'asc'];

            $result = $this->groupRepository->getAll($filters,$sort,$columns);
            $returnData = [];
            foreach ($result as $item) {
                $returnData[] = [
                    'id' => $item->id,
                    'title'=>$item->group_name
                ];
            }
            return $returnData;
        }
    }

    public function getSchoolIdByGroupId($group_id)
    {
        if($group_id == 0) {
            return ['id' => 0, 'group_name' => ''];
        }

        $group_flag = 0;
        $school = [];
        while ($group_flag != 1){
            $group = $this->groupRepository->get($group_id);

            $group_flag = $group['group_flag'];
            $parent_id = $group['parent_id'];
            if($group_flag == 1 || $parent_id == 0){
                $school[] = $group->toArray();
                break;
            }else{
                $group_id = $group['parent_id'];
            }
        }

        return $school;
    }

    //*******************外部调用方法****************************************************
    public function getCore($id, $keyName = 'id',$columns = ['*']){
        return $this->groupRepository->get($id,$keyName,$columns);
    }

    // 获取所有学校
    public function getAllSchoolCore($columns = ['*']){
        $filters = [];
        $filters[] = ['group_flag', '=', 1];

        $sort = ['id' => 'asc'];

        return $this->groupRepository->getAll($filters,$sort,$columns);
    }


    /**
     * @param array $idArr
     * @return array
     * @throws ErrorException
     */
    public function getGroupNameById($idArr)
    {
        if (!is_array($idArr)){
            throw new ErrorException('参数不为数组');
        }
        return $this->groupRepository->getGroupNameById($idArr);
    }



}
